#ifndef TOOLS_MINI_DATABASE_H
#define TOOLS_MINI_DATABASE_H

#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <memory>
#include <mutex>
#include <functional>
#include "Variant.h"
#include <unordered_set>

namespace Tool
{
// 字段类型枚举
enum class FieldType
{
    Int,
    Float,
    Double,
    String,
    Bool,
    Binary,
    Null
};

// 排序方式
enum class SortOrder
{
    Ascending,
    Descending
};

// 条件操作符
enum class ConditionOperator
{
    Equals,
    NotEquals,
    GreaterThan,
    LessThan,
    GreaterOrEqual,
    LessOrEqual,
    Like,
    In,
    NotIn,
    IsNull,
    IsNotNull
};

// 逻辑操作符
enum class LogicalOperator
{
    And,
    Or
};

// 字段定义
struct FieldDefinition
{
    std::string m_name;
    FieldType m_type;
    bool m_isPrimaryKey;
    bool m_isNullable;
    Variant m_defaultValue;
    FieldDefinition(const std::string& name, FieldType type, 
                   bool isPrimaryKey = false, bool isNullable = true,
                   const Variant& defaultValue = Variant())
        : m_name(name)
        , m_type(type)
        , m_isPrimaryKey(isPrimaryKey)
        , m_isNullable(isNullable)
        , m_defaultValue(defaultValue)
    {
    }
};


// 条件表达式
class ExportAPI Condition
{
private:
    std::string m_field;
    ConditionOperator m_op;
    Variant m_value;
    std::vector<Condition> m_conditions;
    LogicalOperator m_logicalOp;
    bool m_isComposite;

public:
    Condition(const std::string& field, ConditionOperator op, const Variant& value);
    Condition(const std::vector<Condition>& conditions, LogicalOperator logicalOp);
    bool Evaluate(const VariantHash& record) const;
};

// 条件构建器
class ExportAPI ConditionBuilder
{
public:
    static Condition Equals(const std::string& field, const Variant& value);
    static Condition NotEquals(const std::string& field, const Variant& value);
    static Condition GreaterThan(const std::string& field, const Variant& value);
    static Condition LessThan(const std::string& field, const Variant& value);
    static Condition GreaterOrEqual(const std::string& field, const Variant& value);
    static Condition LessOrEqual(const std::string& field, const Variant& value);
    static Condition Like(const std::string& field, const std::string& pattern);
    static Condition In(const std::string& field, const std::vector<Variant>& values);
    static Condition NotIn(const std::string& field, const std::vector<Variant>& values);
    static Condition IsNull(const std::string& field);
    static Condition IsNotNull(const std::string& field);
    
    // 组合条件
    static Condition Combine(const std::vector<Condition>& conditions, LogicalOperator op);
    static Condition And(const std::vector<Condition>& conditions);
    static Condition Or(const std::vector<Condition>& conditions);
};


// 表类
class ExportAPI Table
{
private:
    std::string m_name;
    std::vector<FieldDefinition> m_fields;
    std::vector<VariantHash> m_records;
    std::mutex m_mutex;
    std::string m_primaryKey;
    std::unordered_map<Variant, size_t> m_primaryKeyIndex;  // 主键哈希索引
    std::unordered_set<std::string> m_fieldNames;           // 字段名哈希集合
    // 验证记录是否符合表结构

    bool ValidateRecord(const VariantHash& record, bool isInsert = true) const;
    int FindPrimaryKeyIndex(const Variant& value) const;
    Variant ConvertToFieldType(const Variant& value, FieldType type) const;
public:
    Table(const std::string& name, const std::vector<FieldDefinition>& fields);
    const std::string& GetName() const;
    const std::vector<FieldDefinition>& GetFields() const;
    bool Insert(const VariantHash& record);
    std::vector<VariantHash> Query(
        const std::vector<std::string>& fields = {},
        const Condition& condition = Condition("", ConditionOperator::Equals, Variant()),
        const std::map<std::string, SortOrder>& orderBy = {},
        size_t limit = 0,
        size_t offset = 0
    );
    size_t Update(const VariantHash& updates,const Condition& condition = Condition("", ConditionOperator::Equals, Variant()));
    size_t Remove(const Condition& condition = Condition("", ConditionOperator::Equals, Variant()));
    size_t GetRecordCount();
    void Clear();
    bool Load(const std::string& filePath);
    bool Save(const std::string& filePath);
};

// SQL执行结果
struct ExecuteResult
{
    bool m_success;
    std::string m_errorMessage;
    size_t m_affectedRows;
    std::vector<VariantHash> m_result;
    
    ExecuteResult()
        : m_success(false)
        , m_affectedRows(0)
    {
    }
};

// 迷你数据库类
class ExportAPI MiniDatabase
{
private:
    std::string m_filePath;
    std::unordered_map<std::string, std::unique_ptr<Table>> m_tables;
    std::mutex m_mutex;
    bool m_inTransaction;
    std::unordered_map<std::string, std::vector<VariantHash>> m_transactionSnapshots;
    ExecuteResult ParseAndExecute(const std::string& sql);
    
public:
    MiniDatabase(const std::string& filePath = "");
    bool Open(const std::string& filePath);
    void Close();
    bool CreateTable(const std::string& tableName, const std::vector<FieldDefinition>& fields);
    bool DropTable(const std::string& tableName);
    bool TableExists(const std::string& tableName) const;
    Table* GetTable(const std::string& tableName);
    ExecuteResult Execute(const std::string& sql);
    bool BeginTransaction();
    bool CommitTransaction();
    bool RollbackTransaction();
    bool Save();
    bool Load(const std::string& filePath = "");
};

}

#endif // MINI_DATABASE_H
    